package lwk.juc.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SynchronizedTest {
    static List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<Integer>());
    public static void main(String[] args) throws InterruptedException {
        // 先存放1000个值让iterator有值可以遍历
        for (int i = 0; i < 5; i++) {
            synchronizedList.add(i);
        }

        Thread iteratorThread = new Thread(new IteratorRunnable(synchronizedList));
        iteratorThread.start();

        TimeUnit.SECONDS.sleep(1);

        Thread modifyThread = new Thread(new ModifySynchronizeRunnable(synchronizedList));
        modifyThread.start();


    }

    static class IteratorRunnable implements Runnable {
        private List<Integer> list;
        public IteratorRunnable(List<Integer> synchronizeList) {
            this.list = synchronizeList;
        }

        @Override
        public void run() {
            while(true) {
                for (Integer i : list) {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(i + ",");
                }
            }
        }
    }

    static class ModifySynchronizeRunnable implements Runnable {
        private List<Integer> list;

        public ModifySynchronizeRunnable(List<Integer> synchronizeList) {
            this.list = synchronizeList;
        }

        @Override
        public void run() {
            while(true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add(100);
                System.out.println("    modify list container");
            }
        }
    }
}
